<template>
  <div class="login-container">
    <form class="login-form" @submit.prevent="handleSubmit">
      <h2>登录</h2>
      <div class="form-group">
        <label for="username">用户名</label>
        <input 
          id="username"
          v-model="form.username" 
          type="text" 
          required 
          placeholder="请输入用户名"
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input 
          id="password"
          v-model="form.password" 
          type="password" 
          required 
          placeholder="请输入密码"
        />
      </div>
      <button type="submit" class="btn-primary" :disabled="isSubmitting">
        {{ isSubmitting ? '登录中...' : '登录' }}
      </button>
      <button type="button" class="btn-link" @click="goRegister">
        还没有账号？立即注册
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import type { LoginForm } from './types'
import { login } from './service'

const router = useRouter()
const form = ref<LoginForm>({
  username: '',
  password: ''
})
const isSubmitting = ref(false)

const handleSubmit = async () => {
  if (!form.value.username || !form.value.password) {
    alert('请填写用户名和密码')
    return
  }

  try {
    isSubmitting.value = true
    const response = await login(form.value)
    localStorage.setItem('token', response.token)
    alert('登录成功！')
    router.push('/')
  } catch (error) {
    alert('登录失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    isSubmitting.value = false
  }
}

const goRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
@import './style.css';
</style> 